<script setup lang="ts">
// @ts-nocheck
import { computed, ref, h, onMounted } from 'vue';
import { getAdList, addAd, updateAd, deleteAd, uploadFile } from '#/api';
import {
  Button,
  Card,
  Form,
  Input,
  Modal,
  Table,
  message,
  Upload,
} from 'ant-design-vue';
import type { UploadProps } from 'ant-design-vue';

// 仅用于避免 lint 误判"导入未使用"（模板中已使用这些组件）
// 这行不会影响运行时逻辑
void [Button, Card, Form, Input, Modal, Table, Upload];

interface AdSlot {
  id: number;
  name: string;
  description: string;
  imageUrl?: string;
}

// 广告位数据
const slots = ref<AdSlot[]>([]);
const searchName = ref('');

// 前端过滤
const filteredList = computed(() =>
  slots.value.filter(s => !searchName.value || s.name.toLowerCase().includes(searchName.value.toLowerCase()))
);

// 表格列定义
const columns = [
  { title: '名称', dataIndex: 'name', key: 'name' },
  { title: '图片描述', dataIndex: 'description', key: 'description' },
  { 
    title: '图片', 
    key: 'image',
    customRender: ({ record }: any) => {
      const url = (record.image || [])[0];
      return url
        ? h('img', { src: url, class: 'w-16 h-16 object-cover rounded cursor-pointer', onClick: () => window.open(url) })
        : '暂无图片';
    }
  },
  {
    title: '操作',
    key: 'action',
    customRender: ({ record }: any) =>
      h('div', [
        h(
          Button,
          { 
            type: 'link',
            onClick: () => handleEdit(record)
          },
          { default: () => '编辑' },
        ),
        h(
          Button,
          { 
            type: 'link', 
            danger: true,
            onClick: () => handleDelete(record)
          },
          { default: () => '删除' },
        ),
      ]),
  },
];

// 广告位弹窗（新增/编辑共用）
const showModal = ref(false);
const saving = ref(false);
const isEdit = ref(false);
const modalTitle = computed(() => isEdit.value ? '编辑广告位' : '新增广告位');
const currentEditId = ref<number | null>(null);

const addForm = ref({
  name: '',
  description: '',
  image: [] as string[],
});

// 初始加载
onMounted(async () => {
  try {
    const res = await getAdList();
    const list = Array.isArray(res) ? res : (res?.data || []);
    slots.value = list;
  } catch {
    message.error('获取广告位列表失败');
  }
});

// 图片上传相关
const fileList = ref<any[]>([]);
const previewVisible = ref(false);
const previewImage = ref('');

function resetAddForm() {
  addForm.value = {
    name: '',
    description: '',
    image: [],
  };
  fileList.value = [];
}

// 图片上传前的校验（无限制）
const beforeUpload = () => true;

// 上传
async function handleUpload({ file, onSuccess, onError }: any) {
  try {
    const res = await uploadFile(file);
    onSuccess(res?.message || '');
  } catch {
    onError(new Error('上传失败'));
  }
}

function handleRemove() {
  fileList.value = [];
}

// 将文件转换为Base64
function getBase64(img: File, callback: (base64Url: string) => void) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result as string));
  reader.readAsDataURL(img);
}

// 预览图片
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
};

function handleCancel() {
  showModal.value = false;
  resetAddForm();
  isEdit.value = false;
  currentEditId.value = null;
}

// 编辑广告位
function handleEdit(record: AdSlot) {
  isEdit.value = true;
  currentEditId.value = record.id;
  addForm.value = {
    name: record.name,
    description: record.description,
    image: record.image || [],
  };
  // 回显已有图片
  fileList.value = (record.image || []).map((url: string, idx: number) => ({ uid: idx, url, status: 'done' }));
  showModal.value = true;
}

// 删除广告位
async function handleDelete(record: AdSlot) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除"${record.name}"广告位吗？`,
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      try {
        await deleteAd(record.id);
        message.success('删除成功');
        // 重新拉最新列表
        const res = await getAdList();
        slots.value = Array.isArray(res) ? res : (res?.data || []);
      } catch {
        message.error('删除失败');
      }
    }
  });
}

// 校验规则（antd Form 用）
const rules = {
  name: [{ required: true, message: '请输入广告位名称' }],
  description: [{ required: true, message: '请输入图片描述' }],
};

const canSubmit = computed(() =>
  !!addForm.value.name && 
  !!addForm.value.description &&
  fileList.value.length > 0
);

async function handleSubmit() {
  if (!canSubmit.value) {
    message.error('请完善表单信息');
    return;
  }
  saving.value = true;
  
  if (isEdit.value && currentEditId.value !== null) {
        // 编辑：调真实接口
        await updateAd({
          id: currentEditId.value,
          name: addForm.value.name.trim(),
          description: addForm.value.description.trim(),
          image: fileList.value.map((f: any) => f.response || f.url || ''),
        });
        message.success('编辑广告位成功');
        // 重新拉最新列表
        const res = await getAdList();
        slots.value = Array.isArray(res) ? res : (res?.data || []);
      } else {
        // 新增：调真实接口
        await addAd({
          name: addForm.value.name.trim(),
          description: addForm.value.description.trim(),
          image: fileList.value.map((f: any) => f.response || f.url || ''),
        });
        message.success('新增广告位成功');
        // 重新拉最新列表
        const res = await getAdList();
        slots.value = Array.isArray(res) ? res : (res?.data || []);
      }
  
  showModal.value = false;
  resetAddForm();
  isEdit.value = false;
  currentEditId.value = null;
  saving.value = false;
}
</script>

<template>
  <div class="p-4">
    <Card>
      <template #title>
        广告位管理
      </template>
      <template #extra>
        <Button type="primary" @click="showModal = true; isEdit = false; resetAddForm();">新增广告位</Button>
      </template>
      <!-- <div class="text-gray-500 mb-4">支持新增、修改、删除等操作。</div> -->
      <!-- 顶部搜索 -->
      <div class="mb-4 flex gap-3">
        <Input v-model:value="searchName" placeholder="请输入广告位名称" style="width: 240px" />
        <Button @click="searchName = ''">重置</Button>
      </div>
      <Table :columns="columns" :dataSource="filteredList" :pagination="false" :rowKey="r => r.id" />
    </Card>

    <!-- 广告位弹窗（新增/编辑共用） -->
    <Modal
      v-model:open="showModal"
      :confirmLoading="saving"
      :title="modalTitle"
      @ok="handleSubmit"
      @cancel="handleCancel"
      destroyOnClose
      width="600px"
    >
      <Form :model="addForm" :rules="rules" layout="horizontal" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <Form.Item name="name" label="广告位名称" :rules="rules.name">
          <Input v-model:value="addForm.name" placeholder="请输入广告位名称" />
        </Form.Item>
        <Form.Item name="description" label="图片描述" :rules="rules.description">
          <Input v-model:value="addForm.description" placeholder="请输入图片描述" />
        </Form.Item>
        <Form.Item label="广告图片">
          <Upload
            v-model:fileList="fileList"
            list-type="picture-card"
            :customRequest="handleUpload"
            :remove="handleRemove"
            :beforeUpload="beforeUpload"
          >
            <div>选择图片</div>
          </Upload>
          <div class="text-gray-500 text-xs mt-1">支持JPG、PNG格式，大小不超过2MB</div>
        </Form.Item>
      </Form>
      
      <!-- 图片预览 -->
      <Modal
        v-model:open="previewVisible"
        :footer="null"
        title="图片预览"
      >
        <img alt="预览图片" style="width: 100%" :src="previewImage" />
      </Modal>
    </Modal>
  </div>
</template>